package com.hades.common.view

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.hades.common.R
import com.hades.common.databinding.TitleListActivityBinding
import com.hades.common.extend.addAllData
import org.hades.corelib.base.exception.EmptyException
import org.hades.corelib.base.view.CoreDialogFragment
import org.hades.corelib.base.widget.TitleBar
import java.util.concurrent.atomic.AtomicInteger

abstract class BaseListFragment : CoreDialogFragment() ,
    SwipeRefreshLayout.OnRefreshListener,
    BaseQuickAdapter.RequestLoadMoreListener {
    protected lateinit var mToolbar: TitleBar
    protected lateinit var refreshLayout: SwipeRefreshLayout
    protected lateinit var mRecyclerView: RecyclerView

    protected var mRefresh = true // 下拉刷新
    protected var mAutoLoad = true // 自动加载分页

    protected var mStartPage: Int = 1
    protected var mPage: AtomicInteger = AtomicInteger(mStartPage)
    protected var mHasNext: Boolean = false
    protected var mMinPageSize: Int = 14

    protected lateinit var mAdapter: BaseQuickAdapter<Any, BaseViewHolder>

    override fun initByViewBind(layoutInflater: LayoutInflater, viewGroup: ViewGroup?): ViewGroup {
        return TitleListActivityBinding.inflate(layoutInflater).root
    }

    override fun onCreateViews() {
        createViews();
        bindRecyclerView()
    }

    private fun createViews() {
        mToolbar = mRootView.findViewById(R.id.title_bar)
        refreshLayout = mRootView.findViewById(R.id.base_list)
        mRecyclerView = mRootView.findViewById(R.id.rv_recyclerview)
    }

    protected open fun bindRecyclerView() {
        mAdapter = onAdapterCreate()
        mRecyclerView.adapter = mAdapter
        setRefreshEnable()
        setLoadMoreEnable()
        setLoadingView()
    }

    override fun onRefresh() {
        mHasNext = true;
        mPage = AtomicInteger(mStartPage);
        onLoadMoreRequested();
    }

    override fun onLoadMoreRequested() {
        if (mHasNext)
            requestData(mPage.get())
    }

    // 配置LayoutManager、分割线等
    abstract fun onAdapterCreate(): BaseQuickAdapter<Any, BaseViewHolder>
    abstract fun requestData(mPage: Int)

    override fun onStart() {
        super.onStart()
        // 触发OnRefresh
        loadStart()
        onRefresh()
    }

    open fun onLoadEnd() {
        mHasNext = false
        mAdapter.loadMoreEnd()
        loadEnd()
        setEmptyView()
    }

    open fun onLoadComplete() {
        if (mPage.get() == mStartPage && mAdapter.data.size < mMinPageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mPage.incrementAndGet()
            mAdapter.loadMoreComplete()
        }
        loadEnd()
        setEmptyView()
    }


    open fun onLoadFail() {
        mAdapter.loadMoreFail()
        loadEnd()
        setEmptyView()
    }

    protected open fun handleData(@NonNull data: MutableList<Any>) {
        // 分页数据为空，表示没有下一页了，结束加载更多
        if (data.isEmpty() && mPage.get() != mStartPage) {
            onLoadEnd()
            return
        }
        if (mPage.get() == mStartPage) {
            // 第一页，刷新
            mAdapter.setNewData(data)
        } else {
            mAdapter.addAllData(data)
        }
        onLoadComplete()
    }

    override fun handleException(exception: Exception) {
        if (exception is EmptyException) {
            if (mPage.get() == mStartPage)
                mAdapter.setNewData(null);
            onLoadEnd();
        } else {
            super.handleException(exception);
            onLoadFail();
        }
        exception.printStackTrace()
    }

    /***************************刷新相关**************************************/
    protected open fun setRefreshEnable() {
        if (mRefresh) {
            refreshLayout.setOnRefreshListener(this)
        } else {
            refreshLayout.setOnRefreshListener(null)
        }
        refreshLayout.isEnabled = mRefresh
    }

    private fun setLoadMoreEnable() {
        if (mAutoLoad){
            mAdapter.setOnLoadMoreListener(this, mRecyclerView)
        }
    }


    // 方便子类覆盖全局status view
    protected open fun setLoadingView() = mAdapter.apply {
        setEmptyView(org.hades.corelib.R.layout.app_loading_view)
    }

    protected open fun setEmptyView() =  mAdapter.apply {
        setEmptyView(org.hades.corelib.R.layout.app_empty_view)
    }

    // 列表的loading
    override fun loadStart() {
//        if (refreshLayout.isEnabled)
//            refreshLayout.isRefreshing = true
    }

    // 参考loadStart
    override fun loadEnd() {
        if (refreshLayout.isEnabled)
            refreshLayout.isRefreshing = false
    }
}